package com.navi.loaddata.job;

import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.job.QuartzManage;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.loadService.IEtlConfServices2;
import com.navi.loaddata.loadService.impl.opeEqptData.LoadOpeDataService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * LoadOpeData
 *
 * @author Matthew
 * @date 2018-05-04
 */
public class LoadOpeData  implements Job {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private IEtlConfServices2 etlConfServices;

  @Autowired
  private QuartzManage quartzManage;

  @Autowired
  private LoadOpeDataService loadOpeDataService;
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    EtlConfD etlConfD = etlConfServices.getNewConf(context);
    if (null == etlConfD) return;
    etlConfD = etlConfServices.beginJob(etlConfD);
    if (StringUtils.isEmpty(etlConfD.getQueryMinute())) return;
    startETL(etlConfD);
  }

  private void startETL(EtlConfD etlConfD) {
    try {
      int countSize = loadOpeDataService.loadOpeDataMain(etlConfD);
      EtlConfDModel etlConf= etlConfServices.endJobOfModel(etlConfD);
      if (null == etlConf) return;
      String[] resMsg ={"0","0",null};
      EtlConfDModel etlConfDByOpe = etlConfServices.endJobOfModel(etlConfD);
      if (null == etlConfDByOpe) return;
      etlConfServices.addHisOfModel(etlConfDByOpe, resMsg);
    } catch (ETLException2 e) {
      String[] errMsg = null;
      String err = e.getErrMsg();
      errMsg[0] = "0";
      errMsg[1] = "0";
      errMsg[2] = err;
      //print Log
      logger.error("Job {} [{}]-[{}]  FAIL TO SYNCHRONIZE.\n{}\n{}",
          etlConfD.getProjectName() + "_" + etlConfD.getJobGroupName() + "_" + etlConfD.getJobName(),
          etlConfD.getRunStartTimestamp(), etlConfD.getRunEndTimestamp(),
          e.getErrorCode().getErrorMsg(),LoggerUtil.stackTraceToString(e)
      );
      EtlConfDModel etlConfDByOpe = etlConfServices.endJobOfModel(etlConfD);
      if (null == etlConfDByOpe) return;
      etlConfServices.addHisOfModel(etlConfDByOpe, errMsg);

      logger.error(etlConfD.getJobName() + "LoadEdcDataService:lodEdcData" + LoggerUtil.stackTraceToString(e));
    }
    etlConfServices.endJob(etlConfD);
  }
}
